import Promise from 'bluebird'
import Geohash from 'latlon-geohash'
import Res from '@/utils/res.js'

let geoP

let profilePos

const Module = {
  setProfileAddress: function (address) {
    profilePos.formattedAddress = address
    return address
  },
  clean: function () {
    geoP = null
  },
  getGeolocation: function () {
    return new Promise(function (resolve, reject) {
      if (DEBUG) {
        setTimeout(function () {
          resolve({
            address:{"l1_area_id":310000,"l2_area_id":310100,"l3_area_id":310107,"lat":31.23793,"lng":121.41673,"province":"上海市","district":"普陀区","street_address":"曹杨路","detail_street_address":"长风新村街道"},
            geohash: "wtw3dysynu"
          })
        }, 500)
      } else {
        AMap.plugin('AMap.Geolocation', function () {
          let geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 5000,
            convert: false // 标准坐标系
          })
          geolocation.getCurrentPosition()
          AMap.event.addListener(geolocation, 'complete', function (pos) {
            var geohash = Geohash.encode(pos.position.lat, pos.position.lng, 10)
            var address = {}
            var a = pos.addressComponent
            var adcode = parseInt(a.adcode, 10)
            address.l1_area_id = Math.floor(adcode/10000) * 10000
            address.l2_area_id = Math.floor(adcode/100) * 100
            address.l3_area_id = adcode
            address.lat = pos.position.lat
            address.lng = pos.position.lng
            address.province = a.province
            address.district = a.district
            address.street_address = a.street
            address.detail_street_address = a.township
            resolve({geohash:geohash,address:address})
          })

          AMap.event.addListener(geolocation, 'error', function (err) {
            Toast('定位失败')
            let pos = {
              address:{"l1_area_id":310000,"l2_area_id":310100,"l3_area_id":310107,"lat":31.23793,"lng":121.41673,"province":"上海市","district":"普陀区","street_address":"曹杨路","detail_street_address":"长风新村街道"},
              geohash: "wtw3dysynu"
            }
            resolve(pos)
          })
        })
      }
    }).catch(function () {
      return {
            address:{"l1_area_id":310000,"l2_area_id":310100,"l3_area_id":310107,"lat":31.23793,"lng":121.41673,"province":"上海市","district":"普陀区","street_address":"曹杨路","detail_street_address":"长风新村街道"},
            geohash: "wtw3dysynu"
          }
    })
  },
  getAddress: function (lnglat) {
    let p = new Promise(function (resolve, reject) {
     
        AMap.service('AMap.Geocoder',function(){
          let geocoder = new AMap.Geocoder({
          })
          geocoder.getAddress( lnglat , function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              resolve(result)
            } else {
              reject(new Error())
            }
          })
        })
      
    })
    return p
  },
  getTravelTime (distance, startPos, endPos, city) {
    return new Promise(function (resolve) {
      if (distance < 2000) {
        AMap.service('AMap.Walking',function () {
          let walking= new AMap.Walking({city: city?city:'上海'});
          walking.search(startPos, endPos, function(status, result) {
            resolve([status,result])
          });
        });
      } else {
        AMap.service('AMap.Transfer', function () {
          let trans = new AMap.Transfer({city: city?city:'上海', policy: AMap.TransferPolicy.LEAST_TIME });
          trans.search(startPos, endPos, function(status, result) {
            resolve([status,result])
          });
        });
      }
    })
  },

  getBusTime (startPos,endPos,city) {
    return new Promise(function (resolve) {
      AMap.service('AMap.Transfer',function(){
        let trans = new AMap.Transfer({city: city?city:'上海', policy: AMap.TransferPolicy.LEAST_TIME });
        trans.search(startPos, endPos, function(status, result) {
            resolve([status,result])
        });
      }) 
    })

  },

  getWalkTime (startPos,endPos,city) {
    return new Promise(function (resolve) {
       AMap.service('AMap.Walking',function(){
          let walking= new AMap.Walking({city: city?city:'上海'});
          walking.search(startPos, endPos, function(status, result) {
               resolve([status,result])
            });
          }) 
      })
  },

  getDriveTime (startPos,endPos,city) {

    return new Promise(function (resolve) {
      AMap.service('AMap.Driving',function(){
        let driving= new AMap.Driving({city: city?city:'上海'});
        driving.search(startPos, endPos, function(status, result) {
            resolve([status,result])
        });
      }) 
    })
  },

  getAllTime (startPos,endPos,city) {
    return Promise.all([
      Module.getWalkTime(startPos,endPos,city),
      Module.getBusTime(startPos,endPos,city),
      Module.getDriveTime(startPos,endPos,city)
      ]).then(function (arr) {
        return arr
      })
  }
}

function getDistanceFromLatLonInKm(pos1, pos2) {
  let lat1 = pos1.lat
  let lon1 = pos1.lng
  let lat2 = pos2.lat
  let lon2 = pos2.lng
  let R = 6371; // Radius of the earth in km
  let dLat = deg2rad(lat2-lat1);  // deg2rad below
  let dLon = deg2rad(lon2-lon1); 
  let a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
  let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  let d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}

export default Module
